import {
  getLeftData
} from '@admin/api/common'
import {
  listToTree
} from '@admin/utils/index'

export default {
  data() {
    return {
      tabData: [],
      tabLoading: false,
      activeTab: '',
      currentTab: {}
    }
  },
  computed: {
    keyField: function() {
      try {
        return this.tabInfo.keyField || 'code'
      } catch (e) {
        return ''
      }
    },
    relationField: function() {
      try {
        return this.tabInfo.relationField || ''
      } catch (e) {
        return ''
      }
    }
  },
  methods: {
    gettabData() {
      const param = {
        pageId: window.$CD.pageId
      }
      this.tabLoading = true
      return getLeftData(param).then(res => {
        // 处理层级关系
        console.log(this.relationField)
        const data = res.data.map((item) => {
          if (this.tabInfo.displayFields && this.tabInfo.displayFields.length) {
            if (this.tabInfo.displayFields.length == 1) {
              item['TREE_UNION_NAME'] = item[this.tabInfo.displayFields[0]]
            } else {
              const subName = item[this.tabInfo.displayFields[1]]
              item['TREE_UNION_NAME'] = item[this.tabInfo.displayFields[0]] + (subName === undefined ? '' : '(' + subName + ')')
            }
          } else {
            item['TREE_UNION_NAME'] = item['NAME']
          }
          return item
        })
        this.tabData = listToTree(data, this.relationField || 'TYPEID', this.keyField || 'ID', ['', '0', null])
        console.log(this.tabData)
        this.$store.commit('page/SET_TREES', this.tabData)
        // 获取第一个tab
        if (this.tabData.length) {
          this.currentTab = this.tabData[0]
          this.activeTab = 'tab_' + this.currentTab[this.keyField || 'ID']
          this.$store.commit('page/SET_CURRENTTREE', this.currentTab)
          console.log(this.currentTab)
        }
      }).finally(() => {
        this.tabLoading = false
      })
    }
  }
}
